/*
 * max30102.c
 *
 *  Created on: Apr 20, 2025
 *      Author: QkLia
 */

#include"max30102.h"
#include"i2c.h"

#define MAX30103_IIC_HANDLE			&hi2c3
#define MAX30103_IIC_BASE_ADDR		0x57
#define MAX30103_IIC_WRITE_ADDR		((MAX30103_IIC_BASE_ADDR<<1)+0)
#define MAX30103_IIC_READ_ADDR		((MAX30103_IIC_BASE_ADDR<<1)+1)


#define MAX30102_REG_MODE 			0x09
#define MAX30102_REG_INT_STATUS 	0x00
#define MAX30102_REG_INT_EN 		0x02
#define MAX30102_REG_FIFO			0x04
#define MAX30102_REG_FIFO_CONF		0x08
#define MAX30102_REG_SpO2_CONF		0x0A
#define MAX30102_REG_LED_PA			0x0C



void max30102_write_byte(uint8_t reg, uint8_t data){
//	while(HAL_I2C_GetState(MAX30103_IIC_HANDLE) != HAL_I2C_STATE_READY);
	HAL_I2C_Mem_Write(MAX30103_IIC_HANDLE, MAX30103_IIC_WRITE_ADDR, reg, I2C_MEMADD_SIZE_8BIT, &data, 1, 1);
}

void max30102_read_byte(uint8_t reg, uint8_t* data){
//	while(HAL_I2C_GetState(MAX30103_IIC_HANDLE) != HAL_I2C_STATE_READY);
	HAL_I2C_Mem_Read(MAX30103_IIC_HANDLE, MAX30103_IIC_READ_ADDR, reg, I2C_MEMADD_SIZE_8BIT, data, 1, 1);
}

void max30102_init(){

	HAL_Delay(10);

	max30102_write_byte(MAX30102_REG_MODE, 0x40);
	max30102_write_byte(MAX30102_REG_MODE, 0x40);

	max30102_write_byte(MAX30102_REG_INT_EN, 0xC0);
	max30102_write_byte(MAX30102_REG_INT_EN + 1, 0x00);

	max30102_write_byte(MAX30102_REG_FIFO, 0x00);
	max30102_write_byte(MAX30102_REG_FIFO + 1, 0x00);
	max30102_write_byte(MAX30102_REG_FIFO + 2, 0x00);
	max30102_write_byte(MAX30102_REG_FIFO_CONF, 0x0F);

	max30102_write_byte(MAX30102_REG_MODE, 0x03);

	max30102_write_byte(MAX30102_REG_SpO2_CONF, 0x27);

	max30102_write_byte(MAX30102_REG_LED_PA, 0x24);
	max30102_write_byte(MAX30102_REG_LED_PA + 1, 0x24);
	max30102_write_byte(MAX30102_REG_LED_PA + 4, 0x7F);

	max30102_get_int_status();

}

uint8_t max30102_test(){
	uint8_t data=0;
	max30102_read_byte(MAX30102_REG_LED_PA, &data);
	return data;
}

uint16_t max30102_get_int_status(){
	uint8_t temp = 0;
	uint16_t ret = 0;
	max30102_read_byte(MAX30102_REG_INT_STATUS + 1, &temp);
	ret = temp;
	max30102_read_byte(MAX30102_REG_INT_STATUS, &temp);

	return (ret << 8) + temp;
}

uint8_t max30102_fifo_get_data(uint8_t* data){

	// 读取中断状态：清除中断标志位
	max30102_get_int_status();

	uint8_t reg = MAX30102_REG_FIFO + 3;

	HAL_I2C_Master_Transmit(MAX30103_IIC_HANDLE, MAX30103_IIC_WRITE_ADDR, &reg, 1, 1);

	HAL_I2C_Master_Receive(MAX30103_IIC_HANDLE, MAX30103_IIC_READ_ADDR, data, 6, 6);

	return 0;
}
